import { MeshBasicMaterial, TextureLoader, DoubleSide, Mesh, Group, RepeatWrapping, SRGBColorSpace, LinearMipMapLinearFilter, LinearFilter, BoxGeometry, MathUtils, EdgesGeometry, LineBasicMaterial, LineSegments } from 'three'
import { sourceMap } from './pageDate.js'
import { mainStore } from '@/store/mainStore.js'
const store = mainStore()
/**
 * 创建长方体
 * @param   数据体
 * @scene   场景
 * @group   框线组 优化射线性能
 * @returns  无返回
 */
export const updateOrCreateBox = (params, group, colors) => {
  // 查询颜色
  let color = 0x00ff00
  if (store.sourceOrType == '目标') {
    const foundElement = colors.find((element) => element.type.includes(params.class))
    if (foundElement) {
      color = foundElement.color
    }
  } else {
    const foundElement2 = colors.find((element) => element.type === sourceMap[params.source])
    if (foundElement2) {
      color = foundElement2.color
    }
  }
  const geometry = new BoxGeometry(params.width, params.length, params.height)
  // 提取几何体的边缘
  const edgesGeometry = new EdgesGeometry(geometry)
  // 创建材质
  const lineMaterial = new LineBasicMaterial({ color: color }) // 绿色
  // 创建线段对象
  let mesh = new LineSegments(edgesGeometry, lineMaterial)
  if (store.activeTargetId == params.targetId) {
    const material = new MeshBasicMaterial({ color: 0x00ff00, transparent: true, side: DoubleSide })
    mesh = new Mesh(geometry, material)
  }
  mesh.position.set(params.xCoord, params.yCoord, params.zCoord)
  // 转化航向角
  mesh.rotation.z = MathUtils.degToRad(-params.courseAngle)
  mesh.name = 'box_mesh_' + params.targetId
  mesh.targetId = params.targetId
  group.add(mesh)
}
export const updateVideoBox = (params, group, colors) => {
  // 查询颜色
  let color = 0x00ff00
  const foundElement = colors.find((element) => element.type.includes(params.class))
  if (foundElement) {
    color = foundElement.color
  }
  // 查询颜色
  const geometry = new BoxGeometry(params.width, params.length, params.height)
  // 创建线段对象
  const material = new MeshBasicMaterial({ color: color, transparent: true, side: DoubleSide })
  let mesh = new Mesh(geometry, material)
  mesh.position.set(params.xCoord, params.yCoord, params.zCoord)
  // 转化航向角
  // mesh.rotation.z = MathUtils.degToRad(-params.courseAngle)
  // mesh.targetId = params.targetId
  group.add(mesh)
  
}
// 同步纹理贴图加载器
export const texture_loaderSync = (url) => {
  return new Promise((resolve, reject) => {
    const textureLoader = new TextureLoader()
    textureLoader.load(
      url,
      (texture) => {
        texture.colorSpace = SRGBColorSpace
        texture.wrapS = RepeatWrapping
        texture.wrapT = RepeatWrapping
        // 设置纹理高清
        texture.minFilter = LinearMipMapLinearFilter
        texture.magFilter = LinearFilter
        resolve(texture)
      },
      undefined,
      (err) => {
        reject(err)
        console.error(err, '纹理贴图生成失败')
      }
    )
  })
}
